#!/bin/bash

# shellcheck source=meta-facebook/meta-minerva/recipes-minerva/plat-tool/files/minerva-common-functions
source /usr/libexec/minerva-common-functions

# Minerva CMM Sled Power Cycle and Chassis Power Cycle

cmm-hsc-power-cycle() {
    # LTC4287 MFR_REBOOT_CONTROL (FDh) Read/Write
    # [3]:
    #       REBOOT 0 Write a 1 to reboot.
    # [2:0]
    #       RBT_DL 100 Configures Auto-Reboot turn-on Delay (tDL(RBT)) after the REBOOT bit is set to 1
    #       RBT_DL[2:0] DELAY
    #       000 0.580 s
    #       001 1.16 s
    #       010 2.32 s
    #       011 4.64 s
    #       100 9.28 s
    #       101 18.6 s
    #       110 37.1 s
    #       111 74.2 s
    ret1=$(i2cset -y -f 0 0x44 0xfd 0x00)
    ret2=$(i2cset -y -f 0 0x44 0xfd 0x0b)

    # XDP710 RESTART command (0xEC)
    ret3=$(i2cset -f -y 0 0x43 0xec)

    if [ "$ret3" -ne 0 ] && { [ "$ret1" -ne 0 ] || [ "$ret2" -ne 0 ]; }; then
        return 1
    else
        return 0
    fi

}

compute-blade-hsc-power-control() {

    if [ "$1" == "on" ];then
        val=0
    elif [ "$1" == "off" ]; then
        val=1
    else
        return 1
    fi

    for i in {1..16}
    do
        set_gpio "PWREN_MTIA_BLADE${i}_HSC_EN_N" $val
    done
}

network-blade-hsc-power-control() {
    
    if [ "$1" == "on" ];then
        val=0
    elif [ "$1" == "off" ]; then
        val=1
    else
        return 1
    fi
    
    for i in {1..6}
    do
        set_gpio "PWREN_NW_BLADE${i}_HSC_EN_N" $val
    done
}

# CMM Sled Power Cycle
if [ "$1" == 0 ]
then
    echo "Staring CMM Sled Power Cycle"
    cmm-hsc-power-cycle
# CMM Chassis Power Cycle
elif [ "$1" == 1 ]
then
    echo "Staring CMM Chassis Power Cycle"

    compute-blade-hsc-power-control "off"
    network-blade-hsc-power-control "off"
    sleep 15 # sleep 15 seconds to make sure all blades' signal is returned to CMM
    cmm-hsc-power-cycle
else
    echo "Invalid CMM Cycle"
    exit 1
fi
